package cn.yujiago.miaosha.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {

    public static String getValueByKey(HttpServletRequest request, String key){
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0){
            for(Cookie cookie : cookies) {
                if(cookie.getName().equals(key)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    public static void setValueByKey(HttpServletResponse response, String key, String value, int expireSeconds){
        Cookie cookie = new Cookie(key, value);
        cookie.setPath("/");
        cookie.setMaxAge(expireSeconds);
        response.addCookie(cookie);
    }

    public static void addCookie(HttpServletResponse response, Cookie cookie){
        response.addCookie(cookie);
    }
}
